package game;

import static utils.StrategyGameUtils.getResourceTypeForMine;
import net.jcip.annotations.GuardedBy;
import exceptions.*;

public class Mine {
	private int x;
	private int y;
	private Types type;
	@GuardedBy("this")
	private int maxQuantity;
	private int extractedQuantityPerSecond;
	private volatile boolean canMine;

	public Mine(Types type, int maxQuantitiy, int extractedQuantityPerSecond,
			int x, int y) {
		this.x = x;
		this.y = y;
		this.type = type;
		this.maxQuantity = maxQuantitiy;
		this.extractedQuantityPerSecond = extractedQuantityPerSecond;
		this.canMine = true;
	}

	@GuardedBy("this")
	public synchronized Resource mine(long miliseconds)
			throws OutOfOrderException, InterruptedException {
		while (!canMine) {
			wait();
		}
		canMine = false;
		int timeInSeconds = (int) miliseconds / 1000;
		int extractedQuantity = this.extractedQuantityPerSecond * timeInSeconds;
		Types resourceType = getResourceTypeForMine(type);
		if (this.maxQuantity >= extractedQuantity) {
			Thread.sleep(timeInSeconds);
			Resource extracted = new Resource(resourceType, extractedQuantity);
			this.maxQuantity -= extractedQuantity;
			canMine = true;
			notifyAll();
			return extracted;
		} else {
			canMine = true;
			notifyAll();
			throw new OutOfOrderException(" there aren't " + extractedQuantity
					+ " pieces of " + resourceType + " in the " + type);
		}
	}

	public int getX() {
		return x;
	}

	public int getY() {
		return y;
	}

	public boolean equals(Object other) {
		if (!(other instanceof Mine)) {
			return false;
		}
		Mine otherMine = (Mine) other;
		return (x == otherMine.getX() && y == otherMine.getY());
	}
}
